package com.rentong.wx.cust.controller;

import com.rentong.basic.BusinessException;
import com.rentong.basic.ResultInfo;
import com.rentong.common.R;
import com.rentong.common.RedisUtils;
import com.rentong.constants.RedisKeyEnum;
import com.rentong.utils.OssUtil;
import com.rentong.wx.cust.domain.WxCustUser;
import com.rentong.wx.cust.dto.AddInsertInformationDto;
import com.rentong.wx.cust.dto.WxCustUserDto;
import com.rentong.wx.cust.dto.WxUserInfo;
import com.rentong.wx.cust.service.WxCustUserService;
import com.rentong.wx.utils.SendSMS;
import com.rentong.wx.utils.WxApiUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zhangle
 * @Description:
 * @Date: 2018/5/14 13:25
 */
@RestController
public class WxCustUserController {

    @Resource
    private WxCustUserService wxCustUserService;

    @Resource
    private RedisUtils redisUtils;


    /**
     * 209、获取用户信息
     **/
    @PostMapping("/wx/cust/getUserInfo")
    public ResultInfo getUserInfo(WxCustUser wxCustUser, HttpServletRequest request) throws Exception {
        wxCustUser.setCustId(WxApiUtil.getCurrentCustId(request));
        return ResultInfo.success(wxCustUserService.getUserInfo(wxCustUser));
    }

    /**
     * 2、注册手机号（微信小程序版本）
     **/
    @PostMapping("/wx/cust/registerByPhone")
    public ResultInfo registerByPhone(String code, String phone, String phoneCode) throws Exception {
        if (StringUtils.isBlank(code)) {
            throw new BusinessException("缺少code参数");
        }
        WxUserInfo aui = wxCustUserService.registerByPhone(code, phone, phoneCode);
        return ResultInfo.success(aui);
    }
//    /** 2、注册手机号（微信小程序版本） **/
//    @PostMapping("/wx/cust/registerByPhone")
//    public ResultInfo registerByPhone(String code, String encryptedData, String iv)throws Exception{
//        if (StringUtils.isBlank(code)) {
//            throw new BusinessException("缺少code参数");
//        }
//        WxUserInfo aui= wxCustUserService.registerByPhone(code,encryptedData,iv);
//        return ResultInfo.success(aui);
//    }


    /**
     * 33、发送验证码
     **/
    @RequestMapping("/wx/sendCode")
    public ResultInfo sendCode(String phone) {
        //发送验证码
        String code = SendSMS.sendSMS(phone);
        //先删除原来的短信
        redisUtils.delete(RedisKeyEnum.redis_SMS.getKey() + phone);
        //再发送短信
        redisUtils.setTimes(RedisKeyEnum.redis_SMS.getKey() + phone, code, 300L, TimeUnit.SECONDS);

        return ResultInfo.success("发送验证码成功！");
    }


    /*
     * 19、添加个人资料
     *
     * */
    @PutMapping("/wx/cust/updateInformation")
    public R updateInformation(@RequestBody AddInsertInformationDto addInsertInformationDto, HttpServletRequest request) throws Exception {
        addInsertInformationDto.setCustId(WxApiUtil.getCurrentCustId(request));
        Integer integer = wxCustUserService.updateInformation(addInsertInformationDto);
        if (integer > 0) {
            return R.success("操作成功");
        } else {
            return R.error("操作失败");
        }
    }


    /**
     * 21、首页，查询出底部的师傅列表
     * <p>
     * chooseType，1：推荐；2：销量；3：距离；4：价格由高到低；5：价格由低到高
     **/
    @GetMapping("/wx/cust/getChefList")
    public R getChefList(BigDecimal serviceAmountStart, BigDecimal serviceAmountEnd, Integer serviceOrderType, Long bigTypeId, String serviceIds, Integer chooseType, String caixiIds, Long cityId, String content, BigDecimal longitude, BigDecimal latitude, Integer pageNum, Integer pageSize) {
        WxCustUserDto wxCustUserDto = new WxCustUserDto();
        wxCustUserDto.setServiceAmountStart(serviceAmountStart);
        wxCustUserDto.setServiceAmountEnd(serviceAmountEnd);
        wxCustUserDto.setServiceOrderType(serviceOrderType);
        wxCustUserDto.setServiceIds(serviceIds);
        wxCustUserDto.setChooseType(chooseType);
        wxCustUserDto.setBigTypeId(bigTypeId);
        wxCustUserDto.setCaixiIds(caixiIds);
        wxCustUserDto.setCityId(cityId);
        wxCustUserDto.setContent(content);
        wxCustUserDto.setLongitude(longitude);
        wxCustUserDto.setLatitude(latitude);
        wxCustUserDto.setPageSize(pageSize);
        wxCustUserDto.setPageNum(pageNum);

        return R.success(wxCustUserService.getChefList(wxCustUserDto));
    }


    /*
     * 34、添加个人资料
     *
     * */
    @RequestMapping("/wx/uploadPicCos")
    public R videoUpload(@RequestParam("file") MultipartFile file, String phone) throws Exception {
        if (file.isEmpty()) {
            return R.error("传输错误");
        }
        //获得原始文件名，目的是获得文件扩展名
        String fileName = file.getOriginalFilename();
        //获得后缀名
        String extendName = fileName.substring(fileName.lastIndexOf('.'));
        String newFileName = UUID.randomUUID() + extendName;//获得文件的新名字
        //给的路径是否存在
        String savePath = phone + "/";
        String dest = savePath + newFileName;
        InputStream inputStream = file.getInputStream();
        String url = OssUtil.upload(inputStream, dest);
        return R.success(url);//返回新文件地址＋名字
    }

    /**
     * 213、商户认证，提交资料
     **/
    @GetMapping("/wx/cust/updateBizInfo")
    public R updateBizInfo(WxCustUser wxCustUser, HttpServletRequest request) throws Exception {
        wxCustUser.setCustId(WxApiUtil.getCurrentCustId(request));
        wxCustUserService.updateBizInfo(wxCustUser);
        return R.success("操作成功！");
    }

    /**
     * 221、查询师傅详情（厨师介绍）
     **/
    @GetMapping("/wx/cust/getChefDetailChefInfo")
    public R getChefDetailChefInfo(WxCustUserDto wxCustUserDto, HttpServletRequest request) throws Exception {
        wxCustUserDto.setCId(WxApiUtil.getCurrentCustId(request));
        return R.success(wxCustUserService.getChefDetailChefInfo(wxCustUserDto));
    }

    /**
     * 222、查询师傅详情（服务评价）
     **/
    @GetMapping("/wx/cust/getChefDetailServicePingjia")
    public R getChefDetailServicePingjia(WxCustUserDto wxCustUserDto, HttpServletRequest request) throws Exception {
        return R.success(wxCustUserService.getChefDetailServicePingjia(wxCustUserDto));
    }

    /**
     * 225、更新用户信息
     **/
    @GetMapping("/wx/cust/updateUserPicByCustId")
    public R updateUserPicByCustId(WxCustUser wxCustUser, HttpServletRequest request) throws Exception {
        wxCustUser.setCustId(WxApiUtil.getCurrentCustId(request));
        wxCustUserService.updateUserPicByCustId(wxCustUser);
        return R.success("操作成功！");
    }


    /**
     * 230、资料设置页，查询服务介绍
     **/
    @GetMapping("/wx/cust/getChefServiceIntroduce")
    public R getChefServiceIntroduce(WxCustUser wxCustUser, HttpServletRequest request) throws Exception {
        wxCustUser.setCustId(WxApiUtil.getCurrentCustId(request));
        return R.success(wxCustUserService.getChefServiceIntroduce(wxCustUser));
    }

    //127、我的评价
    @PostMapping("/wx/cust/getMyPingjia")
    public R getMyPingjia(HttpServletRequest request, WxCustUserDto wxCustUserDto) throws Exception {
        Long custId = WxApiUtil.getCurrentCustId(request);
        wxCustUserDto.setCustId(custId);
        return R.success(wxCustUserService.getChefDetailServicePingjia(wxCustUserDto));
    }

}
